<template>
  <van-cell-group v-if="type === 'config-mobile' || type === 'mobile'" inset>
    <van-field v-model="input" :placeholder="config.placeholder">
      <template #label>
        <span>{{ config.title }}</span>
      </template>
    </van-field>
  </van-cell-group>
  <div v-if="type === 'config-table' || type === 'table'" class="v-form-item-wrapper">
    <div class="form-item" v-if="config.isEdit">
      <el-input v-model="input" :placeholder="config.placeholder" @change="onChange" />
      <div v-if="config.required" class="required">*</div>
    </div>
    <div class="form-item" v-else>
      {{ input }}
    </div>
    <pre v-if="config.tips"><i class="icon iconfont">&#xe77e;</i>{{ config.tips }}</pre>
    <el-link type="primary" @click="handleSync">
      <i class="el-icon-refresh"></i> 点击自动计算 【{{ config.title }}】
    </el-link>
  </div>
</template>

<script setup lang="ts">
import * as utils from './utils'
const { forms, getFormValueList } = inject<{
  forms: any
  getFormValueList: () => []
}>('forms', {
  forms: [],
  getFormValueList: () => {
    return []
  }
})
const emits = defineEmits(['update'])
const props = defineProps<{
  id: string
  tdId: string
  formType: string
  formTypeName: string
  config: any

  type: string // config table mobile print
  formValue: string
}>()
const formValueList = computed(() => {
  return getFormValueList ? getFormValueList() : []
})
let oldFormValueList = ref<any[]>([])
const input = ref<string>('')
const onChange = () => {
  emits('update', input.value)
}
const handleSync = () => {
  input.value = utils.exportValFn(
    props.config.columns,
    props.config.exportFn,
    forms.value,
    formValueList.value
  )
}
watch(formValueList, async (value: any[]) => {
  // 排除本组件的改变
  const current = value.filter((el: any) => el.key != props.config.key)
  const prev = oldFormValueList.value.filter((el: any) => el.key != props.config.key)
  if (JSON.stringify(current) != JSON.stringify(prev)) {
    input.value = utils.exportValFn(
      props.config.columns,
      props.config.exportFn,
      forms.value,
      formValueList.value
    )
    oldFormValueList.value = JSON.parse(JSON.stringify(value))
    onChange()
  }
})
onMounted(() => {
  if (props.type === 'table') {
    oldFormValueList.value = JSON.parse(JSON.stringify(getFormValueList()))
    if (props.formValue) {
      input.value = props.formValue
    } else {
      input.value = utils.exportValFn(
        props.config.columns,
        props.config.exportFn,
        forms.value,
        formValueList.value
      )
    }
  }
})
</script>
